/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Inet4Address;
import java.util.Vector;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author SafarTimuro
 */
public class ConnectionServer {
    
    LinkedBlockingQueue<GameConnection> clientQueue;
    ServerSocket server;
    Runnable connHandler;
    private AtomicBoolean running;
    
    public ConnectionServer(){
        clientQueue = new LinkedBlockingQueue<GameConnection>();
        running = new AtomicBoolean(false);
        
        try {
            //@todo update this and make an overloaded server connection constructor
            server = new ServerSocket(23, 20, Inet4Address.getLocalHost());
            connHandler = new Runnable() {
                public void run() {
                    while(running.get()){
                        try {
                            //Create the game connection
                            GameConnection client = 
                                    new GameConnection(server.accept());
                            //Queue the client connection for pickup
                            try {
                                clientQueue.put(client);
                            } catch (InterruptedException ex) {
                                Logger.getLogger(ConnectionServer.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } catch (IOException ex) {
                            Logger.getLogger(ConnectionServer.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        Thread.yield();
                    }
                }
            };
        } catch (IOException ex) {
            Logger.getLogger(ConnectionServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public Vector<GameConnection> getPendingConnections(){
        Vector<GameConnection> pending = new Vector<GameConnection>();
        clientQueue.drainTo(pending);
        return pending;
    }
    
    public boolean hasPendingConnections(){
        return !clientQueue.isEmpty();
    }
    
    public void startServer() {
        if(!running.get()) {
            running.set(true);
            connHandler.run();
        }
    }
    
    public void stopServer() {
        //@todo fix this it won't stop the server until a client conn comes in.
        running.set(false);
    }
}
